package com.yabushan.web.controller.activiti;

import com.alibaba.fastjson.JSON;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yabushan.activiti.domain.*;
import com.yabushan.activiti.service.*;
import com.yabushan.activiti.util.*;
import com.yabushan.common.core.controller.BaseController;
import com.yabushan.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.StartFormData;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.form.*;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activiti")
@Slf4j
@Api(tags = "工作流服务")
public class ActivitiController extends BaseController {

	//Logger log = Logger.getLogger(VacationController.class);

	/*
	 * @Inject(name="flowEngineService") private FlowService flowEngineService;
	 */
	@Autowired
	private ProcessDefinitionService processDefinitionService;

	@Autowired
	private ProcessInstanceService processInstanceService;

	@Autowired
	private HistoryQueryService historyQueryService;

	@Autowired
	private FlowUtils flowUtils;
	@Autowired
	private workflowUtilService workflowUtilService;
	@Autowired
	private VacationService vacationService;

	@Autowired
	private FormService formService;

	@Autowired
	private JumpTaskCmdService jumpTaskCmdService;



	/**
	 * 查询流程定义
	 * @param definitionKey
	 * @param isNew
	 * @return
	 */
	@PostMapping("/queryDefVersion")
	@ApiOperation(value = "2.查询流程定义")
	public RestRspVO<List<ProcessDefinitionBean>> queryDefinition(String definitionKey, String isNew) {
		Boolean isOnlyNew = true;
		if ("false".equals(isNew)) {
			isOnlyNew = false;
		}
		RestRspVO<List<ProcessDefinitionBean>> result = new RestRspVO<List<ProcessDefinitionBean>>();
		List<ProcessDefinitionBean> definitionBeanList = new ArrayList<ProcessDefinitionBean>();
		ProcessDefinitionBean processDefinitionBean = null;
		try {
			List<ProcessDefinition> list = processDefinitionService.queryDefinitionsByDefinitionKey(definitionKey, isOnlyNew);
			// flowEngineService.queryDefinitions();
			if (list != null && list.size() > 0) {
				for (ProcessDefinition processDefinition : list) {
					processDefinitionBean = new ProcessDefinitionBean();
					processDefinitionBean.setProcessDefinitionId(processDefinition.getId());
					processDefinitionBean.setProcessDefinitionKey(processDefinition.getKey());
					processDefinitionBean.setProcessDefinitionName(processDefinition.getName());
					processDefinitionBean.setProcessDefinitionResourceBpmn(processDefinition.getResourceName());
					processDefinitionBean.setProcessDefinitionResourcePng(processDefinition.getDiagramResourceName());
					processDefinitionBean.setProcessDefinitionVersion(processDefinition.getVersion());
					processDefinitionBean.setProcessDeploymentId(processDefinition.getDeploymentId());
					definitionBeanList.add(processDefinitionBean);
				}
			}
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(definitionBeanList);
		} catch (Exception e) {
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 获取所有节点
	 *
	 * @param processDefId
	 */
	@PostMapping("/getAllFlowNode")
	@ApiOperation(value = "3.获取所有节点")
	public RestRspVO<List<StepCodeName>> getAllFlowNode(String processDefId) {
		RestRspVO<List<StepCodeName>> result = new RestRspVO<List<StepCodeName>>();
		try {
			List<StepCodeName> list = workflowUtilService.getJbpmNode(processDefId);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(list);
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
		}
		return result;

	}


	@PostMapping("/startFormTask")
	@ApiOperation(value = "4.表单流程——启动任务" )
	@ApiOperationSupport(order = 1)
	public RestRspVO<String> starkFormTask(String processDefinitionKey,String requestUserId,String businessKey, String variables,String isAutoFinishFirstStep){
		RestRspVO<String> result = new RestRspVO<String>();
		result.setCode(ErrMsgType.START_SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.START_SUCCESS.getErrmsg());
		ProcessInstance processInstance=null;
		try {
			if( StringUtils.isNull(variables) || variables.equals("")){
				variables="{}";
			}
			processInstance = processInstanceService.starkFormTask(processDefinitionKey,requestUserId,businessKey,variables);
			if("1".equals(isAutoFinishFirstStep)){
				List<Task> tasks = processInstanceService.queryMySingleTasks(requestUserId, processInstance.getProcessInstanceId());
				if(tasks.size()!=1){
					result.setMessage("流程启动成功，无法完成第一步！获取到的流程任务数为："+tasks.size()+">>>"+tasks.toString());
				}else{
					// fininshFormTask(tasks.get(0).getId(),requestUserId,variables);
					Map request = JSON.parseObject(variables);
					request.put("processInstanceId",processInstance.getId());
					processInstanceService.completeFormTask(tasks.get(0).getId(),requestUserId,request,request,request);
					result.setMessage("流程启动成功，完成第一步!");
				}
			}
			result.setResult(processInstance.getId());

		}catch (Exception e){
			result.setCode(ErrMsgType.START_FAIL.getErrcode());
			result.setMessage(e.toString());
		}

		return result;
	}

	/**
	 * 根据流程环节名称获取初始化办理人信息
	 */
	@PostMapping("/getDealUserByProcessInstanceId")
	@ApiOperation(value = "5.根据流程节点名称获取办理人信息")
	public RestRspVO<NextStepAndUser> getFirstDealUserByKey(String processKey, String userId, String stepName) {
		RestRspVO<NextStepAndUser> resultRestRspVO = new RestRspVO<NextStepAndUser>();
		NextStepAndUser nextStepAndUser = new NextStepAndUser();
		if(StringUtils.isEmpty(stepName)){
			resultRestRspVO.setCode(ErrMsgType.Fail.getErrcode());
			resultRestRspVO.setMessage("请输入节点名称！");
			return resultRestRspVO;
		}
		try {

			nextStepAndUser = vacationService.getFirstUser(processKey, userId, stepName);
			resultRestRspVO.setResult(nextStepAndUser);
			resultRestRspVO.setCode(ErrMsgType.SUCCESS.getErrcode());
			resultRestRspVO.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		} catch (Exception e) {
			resultRestRspVO.setCode(ErrMsgType.Fail.getErrcode());
			resultRestRspVO.setMessage("流程定义不存在");
			log.error(e.getMessage(), e);
		}
		return resultRestRspVO;
	}
	/**
	 * 获取我的待办任务
	 *
	 * @return
	 */
	@PostMapping("/getAllTask")
	@ApiOperation(value = "6.获取我的待办任务",position = 1)
	public RestRspVO<List<TaskInfoBean>> queryAllTask(String userId) {
		RestRspVO<List<TaskInfoBean>> result = new RestRspVO<List<TaskInfoBean>>();
		List<TaskInfoBean> taskinfo = new ArrayList<TaskInfoBean>();
		List<Task> list = new ArrayList<Task>();
		if (Utils.IsEmpty(userId)) {
			result.setCode(ErrMsgType.START_USER_NULL.getErrcode());
			result.setMessage(ErrMsgType.START_USER_NULL.getErrmsg());
			return result;
		}
		try {
			// 个人任务
			List<Task> taskList = processInstanceService.queryMySingleTasks(userId);
			if (taskList != null && taskList.size() > 0) {
				list.addAll(taskList);
			}
			// 组任务
			List<Task> groupTaskList = processInstanceService.queryMyGroupTasks(userId);
			if (groupTaskList != null && groupTaskList.size() > 0) {
				list.addAll(groupTaskList);
			}

			for (Task task : list) {
				taskinfo.add(flowUtils.returnTaskInfo(task));
			}
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			Collections.sort(taskinfo);//排序
			result.setResult(taskinfo);
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
		}
		return result;
	}

	/**
	 * 根据TaskId获取当前任务以及下一步处理人
	 *
	 * @param taskId
	 * @return
	 */
	@PostMapping("/getOneTaskInfo")
	@ApiOperation(value = "7.根据TaskId获取当前任务以及下一步处理人")
	public RestRspVO<TaskInfo> getOneTaskInfo(String taskId) {
		RestRspVO<TaskInfo> result = new RestRspVO<TaskInfo>();
		TaskInfo taskInfo = new TaskInfo();
		try {
			// 获取所有流出线
			List<NextStepAndUser> outLineList = processInstanceService.queryOutComeListByTaskId(taskId);
			// 获取任务
			Task task = processInstanceService.queryTaskInfo(taskId);
			// 根据当前任务获取下一步任务处理人
			List<NextStepAndUser> nextDealUser =null;// vacationService.getNextStepAndUser(task);
			// 获取当前任务处理人
			List<IdentityLink> identityLinks = processInstanceService.getIdentityLinks(taskId);
			StringBuffer buf = new StringBuffer();
			String currentuserId = null;
			if (identityLinks != null && identityLinks.size() != 0) {
				for (IdentityLink identityLink : identityLinks) {
					buf.append(identityLink.getUserId()).append(Constant.SEPARATOR);
				}
			}
			if (buf != null) {
				currentuserId = buf.toString().substring(0, buf.toString().length() - 1);
				taskInfo.setCurrentDealUserId(currentuserId);
			}

			taskInfo.setNextStepAndUser(outLineList);
			taskInfo.setTaskInfoBean(flowUtils.returnTaskInfo(task));
			taskInfo.setAssignee(vacationService.getRequestUserId(taskId));
			result.setResult(taskInfo);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
		}
		return result;
	}

	/**
	 * 指派我的任务
	 *
	 * @param taskId
	 *            任务ID
	 * @param dealUser
	 *            指派处理人的userId
	 * @return
	 */
	@PostMapping("/claimMyTask")
	@ApiOperation(value = "8.指派我的任务")
	public RestRspVO<String> claimMyTask(String taskId, String dealUser) {
		RestRspVO<String> result = new RestRspVO<String>();
		try {
			if (Utils.IsEmpty(taskId) || Utils.IsEmpty(dealUser)) {
				result.setCode(ErrMsgType.Fail.getErrcode());
				result.setMessage("参数传入有空值，请检查！");
				return result;
			}
			// 指派任务
			processInstanceService.claim(taskId, dealUser);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(taskId);
		} catch (ActivitiObjectNotFoundException e1) {
			log.error(e1.toString());
			result.setCode(ErrMsgType.TASK_NOT_FOUND.getErrcode());
			result.setMessage(e1.toString());
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(e.toString());
		}
		return result;
	}

	/**
	 * 转办我的任务
	 *
	 * @param taskId
	 *            任务ID
	 * @param dealUser
	 *            指派处理人的userId
	 * @return
	 */
	@PostMapping("/trunTask")
	@ApiOperation(value = "9.转办我的任务")
	public RestRspVO<String> trunTask(String taskId, String dealUser) {
		RestRspVO<String> result = new RestRspVO<String>();
		try {
			if (Utils.IsEmpty(taskId) || Utils.IsEmpty(dealUser)) {
				result.setCode(ErrMsgType.Fail.getErrcode());
				result.setMessage("参数传入有空值，请检查！");
				return result;
			}
			// 转办任务
			processInstanceService.trunTask(taskId, dealUser);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(taskId);
		} catch (ActivitiObjectNotFoundException e1) {
			log.error(e1.toString());
			result.setCode(ErrMsgType.TASK_NOT_FOUND.getErrcode());
			result.setMessage(e1.toString());
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(e.toString());
		}
		return result;
	}
	/**
	 * 表单流程——保存任务表单
	 * @param taskId
	 * @param formVariables
	 * @param TaskVariables
	 * @return
	 */
	@PostMapping("/saveTask")
	@ApiOperation(value = "10.表单流程——保存任务表单")
	public RestRspVO<String> saveTask(String taskId,String formVariables,String TaskVariables){
		RestRspVO<String> result = new RestRspVO<String>();
		result.setCode(ErrMsgType.SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		if(formVariables==null){
			formVariables="{}";
		}
		if(TaskVariables==null){
			TaskVariables="{}";
		}
		try {
			Map formVariablesMap = JSON.parseObject(formVariables);
			Map TaskVariablesMap = JSON.parseObject(TaskVariables);
			processInstanceService.saveTask(taskId,formVariablesMap,TaskVariablesMap);
		}catch (Exception e){
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
			result.setResult(e.toString());
		}
		return result;
	}


	@PostMapping("/fininshFormTask")
	@ApiOperation(value = "11.表单流程——完成任务")
	public RestRspVO<String> fininshFormTask(String taskId,String userId,String formVariables, String TaskVariables,String excutionVariables){
		RestRspVO<String> result = new RestRspVO<String>();
		result.setCode(ErrMsgType.SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		List<String> multiInstanceUser = new ArrayList<>();
		try {
			if(StringUtils.isNull(formVariables)||formVariables==""){
				formVariables="{}";
			}
			if(StringUtils.isNull(TaskVariables)||TaskVariables==""){
				TaskVariables="{}";
			}
			if(StringUtils.isNull(excutionVariables)||excutionVariables==""){
				excutionVariables="{}";
			}
			Map formVariablesMap = JSON.parseObject(formVariables);
			Map TaskVariablesMap = JSON.parseObject(TaskVariables);
			Map excutionVariablesMaps = JSON.parseObject(excutionVariables);
			processInstanceService.completeFormTask(taskId,userId,formVariablesMap,TaskVariablesMap,excutionVariablesMaps);
		}catch (Exception e){
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
			result.setResult(e.toString());
		}
		return result;
	}

	/**
	 * 部署流程定义
	 *
	 * @return
	 */
	//@PostMapping("/deploy")
	//@ApiOperation(value = "部署流程定义")
	/*public RestRspVO<Deployment> deploy(String deploymentName, String DeployKey) {
		RestRspVO<Deployment> result = new RestRspVO<Deployment>();
		String bpmn = "";
		String png = "";
		if (DeployKey.equals(Constant.VACATION_PROCESS)) {
			// 二级经理正职请假流程
			bpmn = Constant.VACATION_FLOW_BPMN;
			png = Constant.VACATION_FLOW_PNG;
		} else if (DeployKey.equals(Constant.DEPUTY_PROCESS)) {
			// 二级经理副职请假流程
			bpmn = Constant.DEPUTY_FLOW_BPMN;
			png = Constant.DEPUTY_FLOW_PNG;
		} else if (DeployKey.equals(Constant.CANCEL_PROCESS)) {
			// 销假流程
			bpmn = Constant.CANCEL_FLOW_BPMN;
			png = Constant.CANCEL_FLOW_PNG;
		} else if (DeployKey.equals(Constant.VISIT_PROCESS)) {
			// 探亲假流程
			bpmn = Constant.VISIT_FLOW_BPMN;
			png = Constant.VISIT_FLOW_PNG;
		} else if (DeployKey.equals(Constant.JOBEVALUATION_PROCESS)) {
			// 协作满意度评分申请流程
			bpmn = Constant.JOBEVALUATION_FLOW_BPMN;
			png = Constant.JOBEVALUATION_FLOW_PNG;
		} else if (DeployKey.equals(Constant.TRIOUTOFPLAN_PROCESS)) {
			// 培训管理计划外培训管理流程
			bpmn = Constant.TRIOUTOFPLAN_FLOW_BPMN;
			png = Constant.TRIOUTOFPLAN_FLOW_PNG;
		} else {
			result.setCode(ErrMsgType.DEPLOY_FAIL.getErrcode());
			result.setMessage(ErrMsgType.DEPLOY_FAIL.getErrmsg());
			return result;
		}
		try {
			processDefinitionService.DeployByInputStream(deploymentName, bpmn, png, Constant.PROCESS_FILE_ROOT_PATH);
			result.setCode(ErrMsgType.DEPLOY_SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.DEPLOY_SUCCESS.getErrmsg());
			// result.setResult(deployment);
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.DEPLOY_FAIL.getErrcode());
			result.setMessage(ErrMsgType.DEPLOY_FAIL.getErrmsg());
		}
		return result;
	}
*/

	/**
	 * 启动流程实例
	 *
	 *            用户ID
	 * @param businessId
	 *            业务主键ID
	 * @return
	 *         http://localhost:9088/leap_demo_app/hello/start?userName=发哥&businessId
	 *         =4
	 */
	//@PostMapping("/startFlow")
	//@ApiOperation(value = "启动流程实例")
	/*public RestRspVO<String> start(@RequestParam(value="processDefinitionKey",required = true)String processDefinitionKey, @RequestParam(value="userId",required = true)String userId, @RequestParam(required = true)String businessId, @RequestParam(required = true)String nextDealUser, String nextNodeName, String Info, String nextStep, String isJumpStep) {
		// if("".equals(nextStep) || "null".equals(nextDealUser) ||
		// null==nextStep){
		if ("1".equals(isJumpStep)) {
			// 如果是跳过步骤，则步骤名字取输入的，这里不变
		} else {
			nextStep = Constant.DEFULT_STEP;
		}

		RestRspVO<String> result = new RestRspVO<String>();
		if (Utils.IsEmpty(userId)) {
			result.setCode(ErrMsgType.START_USER_NULL.getErrcode());
			result.setMessage(ErrMsgType.START_USER_NULL.getErrmsg());
			return result;
		}
		if (Utils.IsEmpty(businessId)) {
			result.setCode(ErrMsgType.START_BUSINESS_NULL.getErrcode());
			result.setMessage(ErrMsgType.START_BUSINESS_NULL.getErrmsg());
			return result;
		}
		// 启动流程实例的同时，设置流程变量，使用流程变量来指定任务的办理人，对应Hello.pbmn文件中的#(userName)
		try {
			// 使用流程定义的Key启动流程实例
			org.activiti.engine.runtime.ProcessInstance processInstance = processInstanceService.StartProcess(userId, businessId, processDefinitionKey);
			// 获取当前任务,并执行
			List<Task> task = processInstanceService.getMyTasks(userId);
			boolean flag = false;
			for (Task t : task) {
				if (t.getProcessInstanceId().equals(processInstance.getProcessInstanceId())) {
					processInstanceService.completeTask(t.getId(), userId, nextDealUser,nextNodeName,nextStep, Info);
					flag = true;
					result.setResult(t.getProcessInstanceId());
				}
				if (flag)
					break;
			}
			result.setCode(ErrMsgType.START_SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.START_SUCCESS.getErrmsg());

		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.START_FAIL.getErrcode());
			result.setMessage(ErrMsgType.START_FAIL.getErrmsg());
		}
		return result;
	}*/




	/**
	 * 完成我的任务
	 *
	 * @param taskId
	 * @return
	 */
	//@PostMapping("/finishMyTask")
	//@ApiOperation(value = "完成我的任务")
	/*public RestRspVO<String> FinishMyTask(String processInstanceId, String taskId, String userId, String nextDealUserId,String nextNodeName, String stepInfo, String nextSeqFlow) {
		// RestRspVO<List<HistoryTaskInfo>> result =new
		// RestRspVO<List<HistoryTaskInfo>>();
		RestRspVO<String> result = new RestRspVO<String>();
		try {
			// nextSeqFlow=new String(nextSeqFlow.getBytes("utf-8"));
			if (Utils.IsEmpty(nextSeqFlow)) {
				nextSeqFlow = Constant.DEFULT_STEP;
			}
			// 完成任务
			processInstanceService.completeTask(taskId, userId, nextDealUserId, nextNodeName, nextSeqFlow, stepInfo);

			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(processInstanceId);
			*//*
	 * //获取流程记录 List<HistoryTaskInfo> list =
	 * vacationservice.getAllHistoryStep(processInstanceId, false, null,
	 * null); result.setResult(list);
	 *//*
		} catch (ActivitiObjectNotFoundException e1) {
			log.error(e1.toString());
			result.setCode(ErrMsgType.TASK_NOT_FOUND.getErrcode());
			result.setMessage(ErrMsgType.TASK_NOT_FOUND.getErrmsg());
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
		}
		return result;
	}*/










	/**
	 * 根据流程实例ID获取所有流程信息
	 *
	 * @param Id
	 *            业务主键ID 获取流程实例ID
	 * @param flag
	 *            1：业务主键ID,2:流程实例ID
	 * @return
	 */
	@PostMapping("/getAllFlowStep")
	@ApiOperation(value = "12.根据流程实例ID获取所有流程信息，flag:1：业务主键ID,2:流程实例ID")
	public RestRspVO<List<HistoryTaskInfo>> getAllFlowStepById(String Id, String flag) {
		RestRspVO<List<HistoryTaskInfo>> result = new RestRspVO<List<HistoryTaskInfo>>();
		List<HistoryTaskInfo> list = new ArrayList<HistoryTaskInfo>();
		List<HistoricProcessInstance> historicProcessInstances = new ArrayList<HistoricProcessInstance>();
		result.setCode(ErrMsgType.Fail.getErrcode());
		result.setMessage("传入参数不正确！");
		if (Id == null || "".equals(Id)) {
			return result;
		} else {
			if ("1".equals(flag)) {
				// 根据业务主键ID获取历史任务
				// 需要根据业务ID获取所有流程实例
				historicProcessInstances = historyQueryService.getHistoricProcessInstanceByKey(Id, "bid", false, null, null);
				for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
					list.addAll(vacationService.getAllHistoryStep(historicProcessInstance.getId(), false, null, null));
				}
			} else if ("2".equals(flag)) {
				// 根据流程实例ID获取任务
				list = vacationService.getAllHistoryStep(Id, false, null, null);
			} else {
				return result;
			}
		}
		result.setResult(list);
		result.setCode(ErrMsgType.SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		return result;
	}



	/**
	 * 根据流程实例ID获取历史流程步骤
	 *
	 * @param processInstanceId
	 * @return
	 */
	@ApiOperation(value = "13.根据流程实例ID获取历史流程步骤")
	@PostMapping("/getStep")
	public RestRspVO<List<HistoryTaskInfo>> getAllHistoryStep(String processInstanceId) {
		RestRspVO<List<HistoryTaskInfo>> result = new RestRspVO<List<HistoryTaskInfo>>();
		try {
			// 获取流程记录
			List<HistoryTaskInfo> list = vacationService.getAllHistoryStep(processInstanceId, false, null, null);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(list);
		} catch (Exception e) {
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(e.toString());
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 自定义流程
	 * 获取指定流程的 我的待办任务
	 * newAtdV1.0
	 * @param userId
	 * @param processInstanceId 流程ID
	 * @return
	 */
	@ApiOperation(value = "14.根据流程ID，获取我的待办任务")
	@PostMapping("/getMyTaskByProId")
	public RestRspVO<List<TaskInfoBean>> queryMyTaskByProId(String userId, String processInstanceId) {
		RestRspVO<List<TaskInfoBean>> result = new RestRspVO<List<TaskInfoBean>>();
		List<TaskInfoBean> taskinfo = new ArrayList<TaskInfoBean>();
		if (Utils.IsEmpty(userId)) {
			result.setCode(ErrMsgType.START_USER_NULL.getErrcode());
			result.setMessage(ErrMsgType.START_USER_NULL.getErrmsg());
			return result;
		}
		try {
			// 个人任务
			List<Task> taskList = processInstanceService.queryMySingleTasks(userId,processInstanceId);
			for (Task task : taskList) {
				taskinfo.add(flowUtils.returnTaskInfo(task));
			}
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(taskinfo);
		} catch (Exception e) {
			log.error(e.toString());
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
		}
		return result;
	}


	/**
	 * 表单流程——获取启动流程表单信息
	 * @param processDefinitionId
	 * @return
	 */
	@PostMapping("/getStartFormData")
	@ApiOperation(value = "15.表单流程——获取启动流程表单信息")
	public RestRspVO<List<FormInfo>> getStartFormData(String processDefinitionId){
		RestRspVO<List<FormInfo>> result = new RestRspVO<List<FormInfo>>();
		result.setCode(ErrMsgType.START_SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.START_SUCCESS.getErrmsg());
		StartFormData startFormData= formService.getStartFormData(processDefinitionId);
		List<FormProperty> formProperties = startFormData.getFormProperties();
		List<FormInfo> list=new ArrayList<>();
		FormInfo formInfo=null;
		for(int i=0;i<formProperties.size();i++){
			formInfo=new FormInfo();
			formInfo.setId(formProperties.get(i).getId());
			formInfo.setName(formProperties.get(i).getName());
			formInfo.setReadable(formProperties.get(i).isReadable());
			formInfo.setRequired(formProperties.get(i).isRequired());
			formInfo.setValue(formProperties.get(i).getValue());
			if(formProperties.get(i).getType() instanceof DateFormType){
				formInfo.setType("date");
			}else if(formProperties.get(i).getType() instanceof StringFormType){
				formInfo.setType("string");
			}else if(formProperties.get(i).getType() instanceof LongFormType){
				formInfo.setType("long");
			}else if(formProperties.get(i).getType() instanceof EnumFormType){
				formInfo.setType("enum");
			}else if(formProperties.get(i).getType() instanceof BooleanFormType){
				formInfo.setType("boolean");
			}
			list.add(formInfo);

		}
		result.setResult(list);
		return result;
	}


	/**
	 * 表单流程——获取任务表单信息
	 * @param taskId
	 * @return
	 */
	@PostMapping("/getTaskFormData")
	@ApiOperation(value = "16.表单流程——获取任务表单信息")
	public RestRspVO<TaskFormDataImp> getTaskFormData(String taskId) {
		RestRspVO<TaskFormDataImp> result = new RestRspVO<TaskFormDataImp>();
		result.setCode(ErrMsgType.START_SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.START_SUCCESS.getErrmsg());

		TaskFormData taskFormData = formService.getTaskFormData(taskId);
		TaskFormDataImp taskFormDataImp = new TaskFormDataImp();
		taskFormDataImp.setDeploymentId(taskFormData.getDeploymentId());
		taskFormDataImp.setFormKey(taskFormData.getFormKey());
		taskFormDataImp.setAssignee( taskFormData.getTask().getAssignee());
		taskFormDataImp.setCreateTime(taskFormData.getTask().getCreateTime());//
		taskFormDataImp.setId(taskFormData.getTask().getId());
		taskFormDataImp.setName(taskFormData.getTask().getName());
		taskFormDataImp.setProcessInstanceId(taskFormData.getTask().getProcessInstanceId());
		taskFormDataImp.setProcessDefinitionId(taskFormData.getTask().getProcessDefinitionId());
		taskFormDataImp.setFormPropertyImpl(taskFormData.getFormProperties());
		taskFormDataImp.setExecutionId(taskFormData.getTask().getExecutionId());
		taskFormDataImp.setParentTaskId(taskFormData.getTask().getParentTaskId());
		taskFormDataImp.setTaskDefinitionKey(taskFormData.getTask().getTaskDefinitionKey());
		taskFormDataImp.setVariables(taskFormData.getTask().getProcessVariables());
		result.setResult(taskFormDataImp);
		return result;
	}



	/**
	 * 获取我的历史办理任务
	 * @param userId
	 * @param firstResult
	 * @param maxResult
	 * @return
	 */
	@ApiOperation(value = "17.获取我的已办任务")
	@PostMapping("/getMyFinishTask")
	public RestRspVO<List<HistoryTaskInfo>> getMyFinishTask(String userId,Integer firstResult,Integer maxResult) {
		RestRspVO<List<HistoryTaskInfo>> result = new RestRspVO<List<HistoryTaskInfo>>();
		try {
			// 获取流程记录
			List<HistoricTaskInstance> list = historyQueryService.getMyFinishTask(userId, firstResult, maxResult);
			List<HistoryTaskInfo> historyInfo = vacationService.getHistoryInfo(list);
			result.setCode(ErrMsgType.SUCCESS.getErrcode());
			result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
			result.setResult(historyInfo);
		} catch (Exception e) {
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(ErrMsgType.Fail.getErrmsg());
			log.error(e.getMessage(), e);
		}
		return result;
	}


	/**
	 *
	 * @param request
	 * @param response
	 * @param businessKey
	 * @throws Exception
	 */
	@GetMapping("/queryProImg")
	@ApiOperation(value = "18.获取流程图")
	public void queryProImg(HttpServletRequest request, HttpServletResponse response,String businessKey ) throws Exception {
		// 输出资源内容到相应对象
		InputStream imageStream=vacationService.queryProImg(businessKey);
		//FileOutputStream output=new FileOutputStream(new File("d:/test123.png"));
		// 输出资源内容到相应对象
		try {

			//IOUtils.copy(imageStream, output);

			byte[] b = new byte[1024];
			int len;
			response.setContentType("image/png");
			while ((len = imageStream.read(b, 0, 1024)) != -1) {
				response.getOutputStream().write(b, 0, len);
			}
		}finally {
			imageStream.close();
			response.getOutputStream().close();
		}
	}

	/**
	 * 跳转到指定任务节点
	 * @author:yabushan
	 *  @param dkey:流程定义key,businessKey:业务id,stepId:环节ID（startEvent、endEvent）
	 */
	@ApiOperation(value = "19.跳转到指定任务节点")
	@PostMapping("/stopRunProcessInstance")
	public RestRspVO<String> jumpRunProcessInstanceTask(String dkey,String businessKey,String stepId,String taskUserName){
		RestRspVO<String> result = new RestRspVO<String>();
		result.setCode(ErrMsgType.SUCCESS.getErrcode());
		result.setMessage(ErrMsgType.SUCCESS.getErrmsg());
		try {
			jumpTaskCmdService.stopRunProcessInstance(dkey,businessKey,stepId,taskUserName);
		}catch (Exception e){
			result.setCode(ErrMsgType.Fail.getErrcode());
			result.setMessage(e.toString());
		}

		return result;

	}


}
